<template>
  <div class="my-swiper">
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'mySwiper',
  data () {
    return {
      names: [],
      timer: null,
      current: ''
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  watch: {
    value () {
      this.transImg()
    }
  },
  mounted () {
    //  获取当前子组件的所有实例
    console.log(this.$children)
    this.names = this.$children.map(item => item.name)
    console.log(this.names)
    this.transImg()
    this.plays()
  },
  beforeDestroy () {
    clearInterval(this.timer)
  },
  methods: {
    transImg () {
      this.current = this.value || this.$children[0].name
      this.$children.map((item) => {
        item.selected = this.current
      })
    },
    // 自动轮播
    plays () {
      this.timer = setInterval(() => {
        // indexof返回某个指定的字符串首次出现的位置
        const index = this.names.indexOf(this.current)
        let newIndex = index + 1
        if (newIndex === this.names.length) {
          newIndex = 0
        }
        // v-model 是语法糖，等于value + @input
        this.$emit('input', this.names[newIndex])
      }, 3000)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
.my-swiper
  position relative
  border 1px solid #ddd
  width 500px
  height 300px
  overflow hidden
  margin 0 auto
</style>
